import tkinter as tk
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import requests
import os

# 创建窗口
window = tk.Tk()
# 窗口名字
window.title('18AV')
# 窗口大小
window.geometry('300x300')
# 添加组件
row1 = tk.Frame()
# 指定位置
row1.pack(fill="x")
row2 = tk.Frame()
row2.pack(fill="x")
tk.Label(row1, text='抓取地址').pack(side=tk.LEFT)
url = tk.StringVar()
tk.Label(row2, text='保存地址').pack(side=tk.LEFT)
path = tk.StringVar()
tk.Entry(row1, textvariable=url).pack(side=tk.LEFT)
tk.Entry(row2, textvariable=path).pack(side=tk.LEFT)
tk.Button(row1, text="开始寻找", command=lambda: get(
    url.get(), path.get())).pack(side=tk.RIGHT)


def get(url, path):
    # 创建启动方式
    options = webdriver.FirefoxOptions()
    # 隐藏式启动
    options.add_argument('--headless')
    # 创建浏览器options=options
    driver = webdriver.Firefox()
    # 打开指定地址
    driver.get(url)
    #设定页面加载timeout时长，需要的元素能加载出来就行
    driver.set_page_load_timeout(5)
    driver.set_script_timeout(5)
    # 执行按钮
    try:
        driver.find_element_by_xpath("//*[@id='fwin_dialog_submit']").click()
    except:
        driver.execute_script("window.stop()")
    # 定位太慢了
    try:
        driver.find_element_by_xpath("//a[text()='全站随机 H漫画']").click()
    except:
        driver.execute_script("window.stop()")
    try:
        food=driver.find_elements_by_xpath("/html/body/div/div[2]/div[1]/a")
    except:
        driver.execute_script("window.stop()")
    # 循环执行
    for i in food:
        # 执行按钮
        i.click()
        time.sleep(10)
        # 指向弹出页面
        driver.switch_to.window(driver.window_handles[-1])
        # 解析网页
        soup = BeautifulSoup(driver.page_source, "html.parser")
        # 查找指定标签
        opt=soup.find('script',{'language': 'javascript'}).get_text()
        # 去除空格
        opts=''.join(opt.split())
        # 截取字符串
        op=opts.split(r'Large_cgurl=newArray();')[1].split(r';i=0;')[0].split(r';')
        images = []
        # 获取标签名称
        name=soup.find('h1').get_text()
        # 保存地址
        paths=path+'/'+name
        # 创建文件夹
        if os.path.exists(paths) == False:
            os.makedirs(paths)
        # 装入数组
        for i in op:
            images.append(i.split(r'"')[1])
        for o in images:
            # 获取页面
            ir = requests.get(o)
            if ir.status_code == 200:
                # 保存图片
                open(paths+'/'+o[-7:], 'wb').write(ir.content)
        # 关闭当前页面
        driver.close()
    # 关闭浏览器
    driver.quit()

window.mainloop()
